<div
  data-controller="payment-intent"
  data-payment-intent-client-secret-value="<%= @payment.client_secret %>"
  data-payment-intent-status-value="<%= @payment.status %>"
  data-payment-intent-customer-value="<%= @payment.customer %>"
  class="h-screen md:flex md:justify-center md:items-center">
  <div class="w-full max-w-lg">
    <!-- Status Messages -->
    <p data-payment-intent-target="error" class="hidden items-center mb-4 bg-red-100 border border-red-200 px-5 py-2 rounded-lg text-red-500">
      <svg xmlns="http://www.w3.org/2000/svg" class="flex-shrink-0 text-red-500 h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
      </svg>

      <span data-payment-intent-target="errorMessage" class="ml-3"></span>
    </p>

    <p data-payment-intent-target="success" class="hidden items-center mb-4 bg-green-100 border border-green-200 px-5 py-4 rounded-lg text-green-700">
      <svg xmlns="http://www.w3.org/2000/svg" class="flex-shrink-0 text-green-500 h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
      </svg>

      <span data-payment-intent-target="successMessage" class="ml-3"></span>
    </p>

    <div class="bg-white rounded-lg shadow-xl p-4 sm:py-6 sm:px-10 mb-5">
      <% if @payment.succeeded? %>
        <h1 class="text-xl mt-2 mb-4 text-gray-700"><%=t "pay.successful.header" %></h1>
        <p class="mb-6"><%=t "pay.successful.description" %></p>

      <% elsif @payment.canceled? %>
        <h1 class="text-xl mt-2 mb-4 text-gray-700"><%=t "pay.cancelled.header" %></h1>
        <p class="mb-6"><%=t "pay.cancelled.description" %></p>

      <% else %>
        <div data-payment-intent-target="form" id="payment-elements">
          <!-- Instructions -->
          <h1 class="text-xl mt-2 mb-4 text-gray-700"><%=t "pay.requires_action.header", amount: @payment.amount_with_currency %></h1>
          <p class="mb-6"><%=t "pay.requires_action.description" %></p>

          <div data-payment-intent-target="cardFields" class="hidden">
            <!-- Name -->
            <label for="cardholder-name" class="inline-block text-sm text-gray-700 font-semibold mb-2"><%=t "pay.requires_action.full_name" %></label>
            <input data-payment-intent-target="name" id="cardholder-name" type="text" placeholder="Jane Doe" required autofocus class="mt-1 mb-6 block w-full px-3 py-2 rounded-md border border-gray-300 shadow-sm focus:outline-none focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50">

            <!-- Card -->
            <label for="card-element" class="inline-block text-sm text-gray-700 font-semibold mb-2"><%=t "pay.requires_action.card" %></label>
            <div data-payment-intent-target="card" id="card-element" class="mt-1 mb-6 block w-full px-3 py-4 rounded-md border border-gray-300 shadow-sm focus:outline-none focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"></div>
          </div>

          <!-- Pay Button -->
          <button data-payment-intent-target="button" data-action="click->payment-intent#confirmPayment" class="inline-block w-full px-4 py-3 mb-4 text-white rounded-lg bg-blue-400 hover:bg-blue-500">
            <%=t "pay.requires_action.button", amount: @payment.amount_with_currency %>
          </button>
        </div>
      <% end %>

      <%= sanitize link_to(t("pay.back"), @redirect_to, class: "inline-block w-full px-4 py-3 bg-gray-100 hover:bg-gray-200 text-center text-gray-600 rounded-lg") %>
    </div>

    <p class="text-center text-gray-500 text-sm">
      © <%= Date.current.year %> <%= Pay.business_name %> <%=t "pay.all_rights_reserved" %>
    </p>
  </div>
</div>

<script type="module">
  window.stripe = Stripe('<%= Pay::Stripe.public_key %>')

  import { Application, Controller } from 'https://unpkg.com/@hotwired/stimulus/dist/stimulus.js'
  const application = Application.start()

  application.register('payment-intent', class extends Controller {
    static targets = ["error", "errorMessage", "success", "successMessage", "form", "button", "name", "card", "cardFields"]
    static values = {
      clientSecret: String,
      customer: String,
      status: String,
      errorMessage: String,
      successMessage: String,
      complete: Boolean,
      processing: Boolean
    }

    connect() {
      if (this.hasCardTarget) {
        this.elements = stripe.elements({clientSecret: this.clientSecretValue})
        this.payment =  this.elements.create('payment')
        this.payment.mount(this.cardTarget)
      }
    }

    statusValueChanged() {
      switch(this.statusValue) {
        case "requires_action":
          this.processingValue = true
          stripe.confirmPayment({clientSecret: this.clientSecretValue, confirmParams: { return_url: document.location.href }}).then(this.handleConfirmResult.bind(this))
          break
        case "requires_payment_method":
          this.cardFieldsTarget.classList.toggle("hidden", false)
          break
      }
    }

    confirmPayment() {
      this.processingValue = true
      stripe.confirmPayment({elements: this.elements, confirmParams: { return_url: document.location.href }}).then(this.handleConfirmResult.bind(this))
    }

    handleConfirmResult(result) {
      this.processingValue = false

      if (result.error) {
        if (result.error.code === 'parameter_invalid_empty' &&
          result.error.param === 'payment_method_data[billing_details][name]') {
          this.errorMessageValue = '<%=t "pay.requires_action.name_missing" %>'
        } else {
          this.errorMessageValue = result.error.message
          this.statusValue = result.error.payment_intent.status
        }
      } else {
        this.completeValue = true
        this.successMessageValue = '<%=t "pay.requires_action.success" %>'
      }
    }

    completeValueChanged() {
      if (this.hasFormTarget) {
        this.formTarget.classList.toggle("hidden", this.completeValue)
      }
    }

    processingValueChanged() {
      if (this.hasButtonTarget) {
        this.buttonTarget.disabled = this.processingValue
        this.buttonTarget.classList.toggle("bg-blue-400", this.processingValue)
        this.buttonTarget.classList.toggle("bg-blue-500", !this.processingValue)
      }
    }

    errorMessageValueChanged() {
      this.errorMessageTarget.textContent = this.errorMessageValue
      const enabled = (this.errorMessageValue != '')
      this.errorTarget.classList.toggle("flex", enabled)
      this.errorTarget.classList.toggle("hidden", !enabled)
    }

    successMessageValueChanged() {
      this.successMessageTarget.textContent = this.successMessageValue
      const enabled = (this.successMessageValue != '')
      this.successTarget.classList.toggle("flex", enabled)
      this.successTarget.classList.toggle("hidden", !enabled)
    }
  })
</script>
